package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Override
    public void save(Category category) {
        //补全参数
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.save(category);

    }
    /*分页查询类别*/
    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        //设置页面大小
        PageHelper.startPage(page, pageSize);
        //查询数据
        List<Category> categoryList = categoryMapper.findAll();
        //吧集合封装到pageInfo对象中
        PageInfo<Category> categoryPageInfo = new PageInfo<>(categoryList);
        //吧pageInfo数据封装到page中
        Page<Category> cateResult = new Page<>(categoryPageInfo.getList(), categoryPageInfo.getTotal(), page, pageSize);
        return cateResult;
    }

    /*根据id删除类别*/
    @Override
    public void removeById(long id) {
        //查询当前类是否有关联菜品，返回的是菜品总数
        long count = dishMapper.findDishCountByCategoryId(id);
        if (count > 0) {
            throw new CustomException("该类关联了其他菜品，无法删除");
        }
        //查询当前天套餐是否关联其他菜品，
        count = setmealMapper.findSetmealCountByCateGoryId(id);
        if (count > 0) {
            throw new CustomException("该类关联了其他套餐，无法删除");
        }
        categoryMapper.deleteById(id);
    }

    /**
     * 修改类别信息
     */
    @Override
    public void updateById(Category category) {
        //补全信息
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);
    }

    /**
     * 作用：根据Type查询类别集合
     *
     * @param type 类别的type
     * @return
     */
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

}
